package com.jay.net.clazz.socket.udp;

import java.io.IOException;
import java.net.DatagramPacket;

public class ReliableEchoServer implements Runnable {

	ReliableDatagramSocket socket;
	byte[] buffer = new byte[1024];
	DatagramPacket recvPacket = new DatagramPacket(buffer, buffer.length);

	ReliableEchoServer(int port) throws IOException {
		this.socket = new ReliableDatagramSocket(port);
	}

	public void run() {
		for (;;) {
			try {
				// Restore the receive length to the maximum
				recvPacket.setLength(buffer.length);
				socket.receive(recvPacket);
				// Reply must have same seqno as request
				long seqno = socket.getRecvSequenceNo();
				socket.setSendSequenceNo(seqno);
				// Echo the request back as the response
				socket.send(recvPacket);
			} catch (IOException exc) {
				exc.printStackTrace();
			}
		} // for (;;)
	} // run()

}
